package com.sunhao.blog.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sunhao.blog.entity.UserAuth;
import com.sunhao.blog.mapper.UserAuthMapper;
import com.sunhao.blog.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserAuthMapper userAuthMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过账号查询用户
        LambdaQueryWrapper<UserAuth> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAuth::getUsername, username);
        UserAuth user = userAuthMapper.selectOne(lambdaQueryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("not found");
        }

        //定义权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        // TODO: 2024/10/12 数据库查询角色存入权限列表
        // authorities.add(new SimpleGrantedAuthority("ROLE_"+ userInfo.getRole()));

        //最后返回userDetails
        User userDetails = new User(user.getUsername(),passwordEncoder.encode(user.getPassword()),authorities);
        return userDetails;
    }
}
